/*
 * @Author: szx
 * @Date: 2021-12-25 14:08:53
 * @LastEditTime: 2021-12-25 14:59:07
 * @Description:
 * @FilePath: \leetcode\400-499\450\450.js
 */
/**
 * @param {TreeNode} root
 * @param {number} key
 * @return {TreeNode}
 */

var deleteNode = function (root, key) {
    if (root === null) return root;
    // 如果碰上了
    if (root.val === key) {
        // 如果左子节点为空，那么就返回右节点
        if (!root.left) return root.right;
        // 如果右子节点为空，那么就返回右节点
        else if (!root.right) return root.left;
        // 如果右子节点为空，那么就返回右节点
        else {
            let cur = root.right;
            while (cur.left) {
                cur = cur.left;
            }
            cur.left = root.left;
            root = root.right;
            return root;
        }
    }
    if (root.val > key) root.left = deleteNode(root.left, key);
    if (root.val < key) root.right = deleteNode(root.right, key);
    return root;
};
